package com.czp.framework.util;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.czp.user.model.User;
import com.opensymphony.xwork2.ActionContext;

/**
 * 【环 境】：J2SE 1.7
 * @author 柴志鹏
 * @version version 1.0
 * @since 2014-5-4
 */
public class HttpUtils {

	public static ActionContext getActionContext() {
		return ServletActionContext.getContext();
	}

	/** 
	 * 【描 述】：设置Session
	 * @param key
	 * @param value
	 */
	public static void setSession(String key, Object value) {
		Map<String, Object> session = getActionContext().getSession();
		session.put(key, value);
	}

	/** 
	 * 【描 述】：根据key获取指定Session信息
	 * @param key
	 * @return
	 */
	public static Object getSession(Object key) {
		Map<String, Object> session = getActionContext().getSession();
		if (session != null) {
			return session.get(key);
		}
		return null;
	}

	/** 
	 * 【描 述】：根据key删除指定Session信息
	 * @param key
	 */
	public static void removeSession(Object key) {
		Map<String, Object> session = getActionContext().getSession();
		session.remove(key);
	}

	/** 
	 * 【描 述】：清空Session
	 */
	public static void removeAllSession() {
		Map<String, Object> session = getActionContext().getSession();
		System.out.println(session);
		Iterator it = session.keySet().iterator();
		while (it.hasNext()) {
			it.remove();
			System.out.println(it.toString());
		}
	}

	/** 
	 * 【描 述】：初始化用户Session信息
	 * @param user
	 */
	public static void setUserSession(User user) {
//		setSession("userSession", user);
		setSession("userId", user.getId());
		setSession("personId", user.getPersonId());
		setSession("name", user.getName());
		setSession("username", user.getUsername());
	}
	
	/** 
	 * 【描 述】：获取Ip
	 * @param request
	 * @return ip
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
